package com.anyikang.volunteer.sos.volunteer.app.userInfo;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyConstant;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyCurrentOrder;
import com.anyikang.volunteer.sos.volunteer.app.bean.User;
import com.anyikang.volunteer.sos.volunteer.app.main.MainActivity;
import com.anyikang.volunteer.sos.volunteer.utils.ExampleUtil;
import com.anyikang.volunteer.sos.volunteer.utils.MyErrorDeal;
import com.anyikang.volunteer.sos.volunteer.utils.ToastUtils;
import com.anyikang.volunteer.sos.volunteer.utils.okhttputils_callback.StringDialogCallback;
import com.lzy.okhttputils.OkHttpUtils;

import org.json.JSONObject;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author xw.gao
 * 登录页面,登录成功后进入主页
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private Button loginBtn;
    private EditText edtUserName;
    private EditText edtPassword;
    private Handler mHandler = null;
    private static final int MSG_SET_ALIAS = 1001;//设置极光推送别名
    private static final int MSG_SET_TAGS = 1002; //设置极光推送标签
    private static final int CHAT_MSG_UNREAD = 2016; //更新首页聊天未读消息
    private String mUserName;
    private String mPassword;
    String TAG = "LoginActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        createHandler();
    }

    private void initView() {

        loginBtn = (Button) this.findViewById(R.id.loginBtn);
        loginBtn.setOnClickListener(this);
        edtUserName = (EditText) this.findViewById(R.id.edtUserName);
        edtPassword = (EditText) this.findViewById(R.id.edtPassword);

        User user = new User(this);

      //  if(user.isLogin())
        {
            String userName = user.getUserName();
            String password = user.getPassword();

            if(!TextUtils.isEmpty(userName))
            {
                edtUserName.setText(userName);
            }
            else
            {
                return;
            }


            if(!TextUtils.isEmpty(password))
            {
                edtPassword.setText(password);
            }
            else
            {
                return;
            }
        }
        login();//自动登录


        return;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.loginBtn:  //登录成功进入主页
                 login();
          /*      mUserName = edtUserName.getText().toString().trim();
                mPassword = edtPassword.getText().toString().trim();
                if (TextUtils.isEmpty(mUserName)) {
                    ToastUtils.showToast(LoginActivity.this,"用户名不能为空");
                    return;
                }
                if (TextUtils.isEmpty(mPassword)) {
                    ToastUtils.showToast(LoginActivity.this,"密码不能为空");
                    return;
                }
                JPushInterface.setAliasAndTags(getApplicationContext(), (String)mUserName, null, mAliasCallback);
                Intent i = new Intent(LoginActivity.this,MainActivity.class);
                startActivity(i);
                finish();*/
                break;
        }

    }

    public void createHandler()
    {

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_SET_ALIAS:
                        Log.d(TAG, "Set alias in handler.");
                        JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                        break;

                    case MSG_SET_TAGS:
                        Log.d(TAG, "Set tags in handler.");
                        JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mAliasCallback);
                        break;
                    case CHAT_MSG_UNREAD:

                        break;
                    default:
                        Log.i(TAG, "Unhandled msg - " + msg.what);
                }
            }
        };

    }



    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);

                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Log.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }

            //gxw-ExampleUtil.showToast(logs, getApplicationContext());
        }

    };



    /**
     * 成功登录业务服务器后，保存一些用户数据，还要登录环信服务器以后才能聊天
     * @param loginResult: 业务服务器返回的JSON对象

     */
    public void dealLoginSuccess(JSONObject loginResult) {

        try
        {
            JSONObject loginJsonObj = loginResult.getJSONObject("data");
            String userId = loginJsonObj.getString("userId");
            String userName = loginJsonObj.getString("userName");
            String userToken = loginJsonObj.getString("tokenId");

            //登录成功后，设置激光推送别名
            JPushInterface.setAliasAndTags(getApplicationContext(), (String)userName, null, mAliasCallback);

            //保存用户信息到sharepreference.xml，以便以后登录
            ContentValues values = new ContentValues();
            values.put("userId",userId);
            values.put("password",mPassword);
            values.put("userName",mUserName);
            values.put("userToken",userToken);
            User user = new User();
            user.saveUserInfo(LoginActivity.this,values);


            MyCurrentOrder currentOrder = new MyCurrentOrder();
            currentOrder.reset(this);

            //返回结束登录页面
            Intent intent = new Intent();
            intent.putExtra("userId", userId); //服务端接口返回的uid,以后访问需要验证登录的地方都传递uid
            intent.putExtra("userName",userName);//现在都是以电话号为登录账号的
            setResult(RESULT_OK, intent);
            LoginActivity.this.finish();

            Intent i = new Intent(LoginActivity.this,MainActivity.class);  //进入首页
            startActivity(i);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    /**
     * 登录服务器
     */
    private void login() {

        mUserName = edtUserName.getText().toString().trim();
        mPassword = edtPassword.getText().toString().trim();
        if (TextUtils.isEmpty(mUserName)) {
            ToastUtils.showToast(LoginActivity.this,"用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(mPassword)) {
            ToastUtils.showToast(LoginActivity.this,"密码不能为空");
            return;
        }
       //gxw- JPushInterface.setAliasAndTags(getApplicationContext(), (String)mUserName, null, mAliasCallback);

        OkHttpUtils
                .post(MyConstant.API_LOGIN)//
                .tag(MyConstant.API_LOGIN)//
                .params("userName", mUserName)//
                .params("password", mPassword)//
                .execute(new StringDialogCallback(LoginActivity.this) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        int retCode = response.code();
                        if(retCode == 200)
                        {           Log.i(TAG,"onSuccess 200 return："+s);
                            try
                            {
                                JSONObject loginResult = new JSONObject(s);
                                if(loginResult.getString("status").equals("1"))//注册成功后跳转到首页
                                {
                                    //登录成功
                                    dealLoginSuccess(loginResult);
                                }
                                else {
                                    String msg = loginResult.getString("msg");
                                    MyErrorDeal.dealError(msg,LoginActivity.this);
                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            MyErrorDeal.dealHttpError(response,LoginActivity.this);
                            Log.i(TAG,"onSuccess "+retCode+"return: "+s);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

                        MyErrorDeal.dealHttpError(response,LoginActivity.this);

                    }
                });



       /* Intent i = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(i);
        finish();*/
    }
}
